package cn.funeralobjects.util.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author FuneralObjects
 * Create date: 2020/4/16 2:46 PM
 */
public class NormalThreadFactory implements ThreadFactory {

    /**
     * 线程组
     */
    protected ThreadGroup group;
    /**
     * 普通工厂名称
     */
    protected String name;
    /**
     * 序列
     */
    protected AtomicLong threadIndex = new AtomicLong(0L);

    public NormalThreadFactory(String name) {
        this.name = name;
        this.group = GlobalTreadFactory.registerSubThreadGroup(name);
    }

    @Override
    public Thread newThread(Runnable r) {
        return new Thread(group, name + "-[" + threadIndex.incrementAndGet() + "]");
    }

    /**
     * 查看正在运行的线程数量
     *
     * @return 线程数
     */
    public int activeCount() {
        return group.activeCount();
    }

    /**
     * 中断线程组
     */
    public void interrupt() {
        group.interrupt();
    }

    /**
     * 摧毁线程组
     */
    public void destory() {
        if (group.isDestroyed()) {
            return;
        }
        group.destroy();
    }
}
